<template>
  <div id="app">
    <NavBar 
      :isLoggedIn="isLoggedIn" 
      :userRole="userRole" 
      :userAvatar="userAvatar"
      :username="username"  
      @logout="handleLogout" 
    />
    <router-view 
      :username="username" 
      :userAvatar="userAvatar" 
      @loginSuccess="handleLogin"
    />
    <AppFooter/> <!-- 引入页脚组件 -->
  </div>
</template>

<script>
import NavBar from './components/NavBar.vue';
import AppFooter from './components/AppFooter.vue';
import { provide } from 'vue';
import { ref} from'vue'
export default {
  name: 'App',
  components: {
    NavBar,
    AppFooter
  },
  data() {
    const userId = ref(localStorage.getItem('id'));
    console.log(userId);
    provide('userId', userId);
    return {
      isLoggedIn: false,
      userRole: '',
      userAvatar: 'https://via.placeholder.com/40',
      username: '',  
      lastLoginTime: '' // 添加上次登录时间
    };
  },
  methods: {
    handleLogin(role, avatarUrl, username,id) {
      console.log('接收到的登录信息:', { role, avatarUrl, username,id });

      this.isLoggedIn = true;
      this.userRole = role;
      this.userAvatar = avatarUrl;  
      this.username = username;
      this.id=id;

      // 保存到 localStorage
      localStorage.setItem('userRole', role);
      localStorage.setItem('userAvatar', avatarUrl);
      localStorage.setItem('username', username);
      localStorage.setItem('id', id);
    },
    handleLogout() {
      this.isLoggedIn = false;
      this.userRole = '';
      this.userAvatar = 'https://via.placeholder.com/40';
      this.username = '';

      // 清除 localStorage
      localStorage.removeItem('userRole');
      localStorage.removeItem('userAvatar');
      localStorage.removeItem('username');
      localStorage.removeItem('id');
      localStorage.removeItem('token'); 
      localStorage.removeItem('lastLoginTime');
    },
    restoreUserState() {
      const role = localStorage.getItem('userRole');
      const avatarUrl = localStorage.getItem('userAvatar');
      const username = localStorage.getItem('username');
      const token = localStorage.getItem('token');
      const lastLoginTime = localStorage.getItem('lastLoginTime');

      if (token) {
        this.isLoggedIn = true;
        this.userRole = role || '';
        this.userAvatar = avatarUrl || 'https://via.placeholder.com/40';
        this.username = username || '';
        this.lastLoginTime = lastLoginTime || '';
      }
    }
  },
  mounted() {
    this.restoreUserState(); 
  }
};
</script>

<style scoped>
</style>
